package com.tianquan.client.handler;

import com.tianquan.client.registry.ClientInstanceManager;
import com.tianquan.common.instance.ServiceInstance;
import com.tianquan.common.message.PullServiceResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;

/**
 *@Author: tianquan
 *@date: 2024-11-03  17:16
 *@Description: 响应拉取服务实例
 */
@Slf4j
@ChannelHandler.Sharable
public class PullServiceResponseMessageHandler extends SimpleChannelInboundHandler<PullServiceResponseMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, PullServiceResponseMessage pullServiceResponseMessage) throws Exception {
        if (pullServiceResponseMessage.isSuccess()) {
            Map<String, Set<ServiceInstance>> instances = pullServiceResponseMessage.getInstances();
            ClientInstanceManager.clear();
            // 更新本地服务实例列表
            log.info("------------------更新本地服务实例列表-----------------");
            instances.forEach((serviceName, serviceInstances) -> {
                for (ServiceInstance serviceInstance : serviceInstances) {
                    log.info("更新本地服务实例列表: {}",serviceInstance);
                    ClientInstanceManager.registerInstance(serviceName, serviceInstance);
                }
            });
            log.info("更新完后本地服务实例列表{}", ClientInstanceManager.getInstances());
        }

    }

}
